package com.gome.wechat.program.service.applicationservice.impl;

import com.gome.wechat.program.common.util.MyBeanUtil;
import com.gome.wechat.program.dto.UserDto;
import com.gome.wechat.program.entity.User;
import com.gome.wechat.program.entity.UserHobbyTag;
import com.gome.wechat.program.service.UserHobbyTagService;
import com.gome.wechat.program.service.UserService;
import com.gome.wechat.program.service.applicationservice.UserApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liwei113 on 2017/11/1 0001.
 */
@Service
public class UserApplicationServiceImpl implements UserApplicationService {


    @Autowired
    UserService userService;

    @Autowired
    UserHobbyTagService userHobbyTagService;

    @Override
    @Transactional
    public UserDto saveOrUpdateUser(UserDto userDto) {
        Long userId = userDto.getId();
        User user = null;
        if(userId!=null){
            userHobbyTagService.deleteByUserId(userId);
            user = userService.findById(userId);
            MyBeanUtil.copyProperties(userDto,user);

        }else {
            user = User.create(userDto.getId(),userDto.getHeadImage(),userDto.getName(),
                    userDto.getOpenId(),userDto.getSex(),userDto.getAge(),userDto.getIntroduction());
        }
        userService.save(user);
        List<Long> hobbyIds = userDto.getHobbyIds();
        List<UserHobbyTag> userHobbyTags = transform(userId,hobbyIds);
        if(!CollectionUtils.isEmpty(userHobbyTags)){
            userHobbyTagService.saveList(userHobbyTags);
        }
        userDto.setId(userId);
        return userDto;
    }




    private List<UserHobbyTag> transform(Long userId,List<Long> hobbyIds){
        List<UserHobbyTag> result = new ArrayList<>();
        if(!CollectionUtils.isEmpty(hobbyIds)){
            for(Long temp:hobbyIds){
                result.add(new UserHobbyTag(userId,temp));
            }
        }
        return result;
    }
}
